package io.xiaojl.xj2ee.task.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.xiaojl.xj2ee.task.entity.ScheduleJobEntity;
import io.xiaojl.xj2ee.task.mapper.ScheduleJobEntityMapper;
import io.xiaojl.xj2ee.task.service.ScheduleJobService;
import io.xiaojl.xj2ee.task.utils.PageWrapper;
import io.xiaojl.xj2ee.task.utils.ScheduleUtils;
import io.xiaojl.xj2ee.task.utils.Xj2eeTaskConstants;

@Service("scheduleJobService")
public class ScheduleJobServiceImpl implements ScheduleJobService {
	private static final Logger log = LoggerFactory.getLogger(ScheduleJobServiceImpl.class);
	@Autowired
    private Scheduler scheduler;
	@Autowired
	private ScheduleJobEntityMapper baseMapper;
	
	/**
	 * 项目启动时，初始化定时器
	 */
	@PostConstruct
	public void init(){
		try {
			List<ScheduleJobEntity> scheduleJobList = baseMapper.selectAll();
			for(ScheduleJobEntity scheduleJob : scheduleJobList){
				CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
			    //如果不存在，则创建
			    if(cronTrigger == null) {
			        ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
			    }else {
			        ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
			    }
			}
		} catch (Exception e) {
			log.error("项目启动时，初始化定时器出现异常：",e);
		}
	}

	@Override
	public PageWrapper<ScheduleJobEntity> queryPage(Map<String, Object> params) {
		PageWrapper<ScheduleJobEntity> pageWrapper = new PageWrapper<>(params);
		PageHelper.startPage(pageWrapper.getCurrPage(), pageWrapper.getPageSize(), pageWrapper.getOrderBy());
		
		List<ScheduleJobEntity> list = baseMapper.selectListByPage(pageWrapper.getCondition());
		PageInfo<ScheduleJobEntity> page = new PageInfo<>(list);
		
		pageWrapper.setList(page.getList());
		pageWrapper.setTotalCount(Integer.parseInt(page.getTotal()+""));
		pageWrapper.setTotalPage(page.getPages());
        return pageWrapper;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(ScheduleJobEntity scheduleJob) {
		scheduleJob.setCreateTime(new Date());
		scheduleJob.setStatus(Byte.valueOf(Xj2eeTaskConstants.ScheduleStatus.NORMAL.getValue()+""));
		baseMapper.insertSelective(scheduleJob);
        
        ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
    }
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(ScheduleJobEntity scheduleJob) {
        ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
        
        baseMapper.updateByPrimaryKeySelective(scheduleJob);
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		//删除定时任务
    		ScheduleUtils.deleteScheduleJob(scheduler, jobId);
    		
    		//删除数据
    		baseMapper.deleteByPrimaryKey(jobId);
    	}
	}

	@Override
    public int updateBatch(Long[] jobIds, int status){
		return baseMapper.updateStatusByIds(jobIds,status);
    }
    
	@Override
	@Transactional(rollbackFor = Exception.class)
    public void run(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		ScheduleUtils.run(scheduler, baseMapper.selectByPrimaryKey(jobId));
    	}
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void pause(Long[] jobIds) {
        for(Long jobId : jobIds){
    		ScheduleUtils.pauseJob(scheduler, jobId);
    	}
        
    	updateBatch(jobIds, Xj2eeTaskConstants.ScheduleStatus.PAUSE.getValue());
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void resume(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		ScheduleUtils.resumeJob(scheduler, jobId);
    	}

    	updateBatch(jobIds, Xj2eeTaskConstants.ScheduleStatus.NORMAL.getValue());
    }

	@Override
	public ScheduleJobEntity selectById(Long jobId) {
		return baseMapper.selectByPrimaryKey(jobId);
	}
    
}
